// This insane code brought to you by: nerd_boy
//                                     http://www.rated-n-for-nerd.com
var gamerTag="";
var prefs;

function showGamerCard()
{
	console.log("Starting 'showGamerCard()'");
	
	document.getElementById('gamercardcontentID').innerHTML='<iframe src="http://gamercard.xbox.com/'+gamerTag+'.card" scrolling="no" frameBorder="0" height="140" width="204">'+gamerTag+'</iframe>';
	
	console.log("Leaving 'showGamerCard()'");
}

function editGamerCard()
{
	console.log("Starting 'editGamerCard()'");
	
	if(wave.getHost()==null||
	   wave.getHost().getId()==wave.getViewer().getId())
	{
		var html='';
		
		gamerTag=gamerTag.replace("%20"," ");
		
		html+='<input type="button" value="Set Gamer Tag"  onClick="editGamerCardButtonClicked()"></input>';
		html+='<input id="gamertagInputField" type="text" value="'+gamerTag+'"></input>';
		html+='<span id="submittingtext"></span>';
		
		document.getElementById('gamercardcontentID').innerHTML=html;
	}
	else
	{
		showGamerCard();
	}
		
	console.log("Leaving 'editGamerCard()'");
}

function editGamerCardButtonClicked(button)
{
	console.log("Starting 'editGamerCardButtonClicked(button)'");

	gamerTag=document.getElementById('gamertagInputField').value.replace(" ","%20");
	wave.getState().submitValue('gamerTag',gamerTag);
	document.getElementById('submittingtext').innerHTML='Submitting...';
	
	console.log("Leaving 'editGamerCardButtonClicked(button)'");
}

function receiveState()
{
	console.log("Starting 'receiveState()'");

	gamerTag=wave.getState().get('gamerTag');
	
	switch(wave.getMode())
	{
		case wave.Mode.EDIT:
			var submittingText=document.getElementById('submittingtext');
			if(submittingText)
			{
				submittingText.innerHTML='';
			}
			console.log('Gamer Tag successfully changed to '+gamerTag);
		break;
		case wave.Mode.VIEW:
			showGamerCard();
		break;
	}
	
	console.log("Leaving 'receiveState()'");
}

function receiveMode(mode)
{
	console.log("Starting 'receiveMode(mod)'");

	switch(mode)
	{
		case wave.Mode.EDIT:
			editGamerCard();
		break;
		case wave.Mode.VIEW:
			showGamerCard();
		break;
	}
	
	console.log("Leaving 'receiveMode(mod)'");
}

function initialize()
{
	console.log("Starting 'initialize()'");
	
	if(wave&&wave.isInWaveContainer())
	{
		wave.setStateCallback(receiveState);
		wave.setModeCallback(receiveMode);
	}
	
	console.log("Leaving 'initialize()'");
}

gadgets.util.registerOnLoadHandler(initialize);